#include "privatechat.h"
#include "ui_privatechat.h"
#include "tcpclient.h"
#include <QMessageBox>

PrivateChat::PrivateChat(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::PrivateChat)
{
    ui->setupUi(this);
}

PrivateChat::~PrivateChat()
{
    delete ui;
}

PrivateChat &PrivateChat::getInstance()
{
    static PrivateChat instance;
    return instance;
}

void PrivateChat::setChatName(QString strName)
{
    m_strChatName = strName;
    m_strLoginName = TcpClient::getInstance().getloginName();
}

void PrivateChat::updateMsg(const PDU *pdu)
{
    if(NULL == pdu){
        return;
    }
    char caSendName[CADATEMAX] = {'\0'};
    memcpy(caSendName, pdu->caData, CADATEMAX);
    QString strMsg = QString("%1 says: %2").arg(caSendName).arg(pdu->caMsg);
    ui->showMsg_te->append(strMsg);

}

void PrivateChat::on_sendMsg_pd_clicked()
{
    QString strMsg = ui->inputMsg_le->text();

    if(strMsg.isEmpty())
    {
        QMessageBox::warning(this, "私聊","发送的信息不能为空！");
    }else{
        PDU *pdu = mkPDU(strMsg.size()+ 1);
        pdu->uiMsgType = ENUM_MSG_TYPE_PRIVATE_CHAT_REQUEST;
        memcpy(pdu->caData, m_strLoginName.toStdString().c_str(), m_strLoginName.size());
        memcpy(pdu->caData + CADATEMAX, m_strChatName.toStdString().c_str(), m_strChatName.size());
        qDebug()<<QString(pdu->caData + CADATEMAX);
        strcpy(pdu->caMsg, strMsg.toStdString().c_str());
        qDebug()<<QString(pdu->caMsg);
        TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);
        free(pdu);
        pdu = NULL;
        //回显
        QString htmlMsg = QString("<div style='color:blue;'>%1 says: %2</div>")
                              .arg(m_strLoginName)
                              .arg(strMsg);
        ui->showMsg_te->append(htmlMsg);
        ui->inputMsg_le->clear();
    }

}



